//
//  CZLabel.swift
//  TextKitDemo
//
//  Created by tuimao on 2017/8/17.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit

class CZLabel: UILabel {

/// 属性文本的储存
fileprivate lazy var textStorage = NSTextStorage()
/// 负责文本字形处理
fileprivate lazy var layoutManager = NSLayoutManager()
/// 设定文本绘制的范围
fileprivate lazy var textContainer = NSTextContainer()
    
    override var text: String?{
        didSet{
            //重新准备文本内容
            prepareTextContent()
        }
    }
    
    ///初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareTextSystem()
    }
    required init?(coder aDecoder: NSCoder) {
       super.init(coder: aDecoder)
        prepareTextSystem()
    }
    /// 设置绘制区域
    override func layoutSubviews() {
        super.layoutSubviews()
        textContainer.size = bounds.size
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //点击的位置
        guard let location = touches.first?.location(in: self) else{
            return
        }
        //在layoutManager确定文本的具体位置
        let idx = layoutManager.glyphIndex(for: location, in: textContainer)
        for r in urlRanges ?? []{
            //比对正则匹配之后的字符串位置 -> Bool
            if NSLocationInRange(idx, r) {
                //设置背景和字体
                textStorage.addAttributes([NSForegroundColorAttributeName:UIColor.black,NSBackgroundColorAttributeName:UIColor.lightGray], range: r)
                //更新draw
                setNeedsDisplay()
            }else{
                print("没点到")
            }
        }
    }
    
    
    //绘制,ios所有的draw方法都是油画的设计，后面的画的盖住前面的，所以不要用透明，因为GPU要算渲染度很麻烦
    override func drawText(in rect: CGRect) {
        //绘制字形位置
        let range = NSRange(location: 0, length: textStorage.length)
        //要先画背景
        layoutManager.drawBackground(forGlyphRange: range, at: CGPoint())
        //再画文字
        layoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint())
    }
}

//MARK: textKit的核心对象创建
private extension CZLabel{
    /// 准备文本系统
    func prepareTextSystem(){
        /// 0.允许交互
        isUserInteractionEnabled = true
        /// 1.准备文本内容
        prepareTextContent()
        /// 2.设置对象关系
        textStorage.addLayoutManager(layoutManager)
        layoutManager.addTextContainer(textContainer)
    }
    /// 准备文本内容,让textStorage接管label
    func prepareTextContent(){
        if let attributedText = attributedText {
            textStorage.setAttributedString(attributedText)
        }else if let text = text {
            textStorage.setAttributedString(NSAttributedString(string: text))
        }else{
            textStorage.setAttributedString(NSAttributedString(string: ""))
        }
        //查找匹配的位置,并修改
        //修改字体颜色和背景颜色
        for r in urlRanges ?? []{
            textStorage.addAttributes([NSForegroundColorAttributeName:UIColor.blue], range: r)
        }
    }
}
//MARK: 正则筛选url
private extension CZLabel{
    var urlRanges:[NSRange]?{
        let pattern = "[a-zA-Z]*://[a-zA-Z0-9/\\.]*"
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else{
            return nil
        }
        let matches = regx.matches(in: textStorage.string, options: [], range: NSRange(location: 0, length: textStorage.length))
        var ranges = [NSRange]()
        
        for m in matches {
            ranges.append(m.rangeAt(0))
            
        }
        
    return ranges
    }
}



